<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{

    /**
     * 图片上传
     */
    public function upload(Request $request)
    {

        //获取文件name值
        $file = $request->file('files');
        if ($file->isValid()) {
            $ext = $file->getClientOriginalExtension();
            $file_name = date("YmdHis", time()) . '-' . uniqid() . '.' . $ext;
            if (!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) return response()->json(['msg' => '文件类型不是图片']);

//            $path = public_path() . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . 'pictures';

            $path = $file->getRealPath();
            $bool = Storage::disk('oss')->put($file_name, file_get_contents($path));
            if ($bool) {
                /*$img_path = '/uploads/pictures/' . $file_name;
                $data = [
                    'img_path' => env('APP_URL') . $img_path,
                ];*/
                $data = [
                    'img_path' => Storage::url($file_name),
                ];
                return response()->json(['code' => 200, 'msg' => '上传成功', 'data' => $data]);
            } else {
                return response()->json(['code' => 404, 'msg' => '获取路径失败']);
            }
        } else {
            return response()->json(['msg' => '图片上传失败']);
        }
    }

    public function uploadW(Request $request)
    {
        $i = 0;
        $data = [];

        if (!$request->hasFile('pic')) {
            $i = 1;
        }

        try {
            while ($request->hasFile('pic' . ($i > 0 ? $i : ''))) {
                $file = $request->file('pic' . ($i > 0 ? $i : ''));

                if (!$file->isValid()) {
                    throw new \Exception('图片上传失败');
                }

                $ext = $file->getClientOriginalExtension();
                if (!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) {
                    throw new \Exception('文件类型不是图片');
                }

                $file_name = date("YmdHis", time()) . '-' . uniqid() . '.' . $ext;
                $path = $file->getRealPath();
                $bool = Storage::disk('oss')->put($file_name, file_get_contents($path));

                if (!$bool) {
                    throw new \Exception('图片上传失败');
                }

                $data[] = [
                    'url'  => Storage::url($file_name),
                    'alt'  => "",
                    'href' => ""
                ];

                $i++;
            }
        }catch (\Throwable $e) {
            return response()->json(['errno' => 1, 'msg' => $e->getMessage()]);
        }

        return $data ?  response()->json(['errno' => 0, 'data' => $data]) : response()->json(['errno' => 1, 'msg' => '图片上传失败']);
    }

    public function uploadU(Request $request)
    {
        //获取文件name值
        $action = $request->input('action');
        if ($action == 'catch-image') {
            $pics = $request->pic;
            $imges = [];
            foreach ($pics as $pic) {
                $res = $this->saveRemote($pic);
                if ($res['state'] == 'SUCCESS') {
                    $imges[] = [
                        'url' => $res['url'],
                        'source' => $pic,
                        'state' => 'SUCCESS',
                    ];
                }
            }
            $res = [
                'state' => 'SUCCESS',
                'list' => $imges,
            ];
            return response()->json($res);
        } else {
            $file = $request->file('pic');
            if ($file->isValid()) {
                $ext = $file->getClientOriginalExtension();
                $file_name = date("YmdHis", time()) . '-' . uniqid() . '.' . $ext;
                if (!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) return response()->json(['msg' => '文件类型不是图片']);

                $path = $file->getRealPath();
                $bool = Storage::disk('oss')->put($file_name, file_get_contents($path));

                if ($bool) {
                    $res = [
                        'state' => 'SUCCESS',
                        'url' => Storage::url($file_name),
                        "title" => $file_name,
                        "original" => $file_name
                    ];
                    return response()->json($res);
                } else {
                    return response()->json();
                }
            } else {
                return response()->json(['msg' => '图片上传失败']);
            }
        }
    }


    /**
     * 拉取远程图片
     * @return mixed
     */
    private function saveRemote($pic)
    {
        $aext = explode('.', $pic);
        $ext = end($aext);

        if (!in_array($ext, ['jpg', 'png', 'jpeg', 'gif'])) {
            $ext = 'png';
        }
        $file_name = date("YmdHis", time()) . '-' . uniqid() . '.' . $ext;

        $bool = Storage::disk('oss')->put($file_name, file_get_contents($pic));
        if ($bool) {
            $res = [
                'state' => 'SUCCESS',
                'url' => Storage::url($file_name),
                "title" => $file_name,
                "original" => $file_name
            ];
        } else {
            $res = [
                'state' => 'ERROR',
            ];
        }
        return $res;
    }

    private function getHttpHead($url)
    {
        $url = parse_url($url);
        if ($fp = @fsockopen($url['host'], empty($url['port']) ? 80 : $url['port'], $error)) {
            fputs($fp, "GET " . (empty($url['path']) ? '/' : $url['path']) . " HTTP/1.1\r\n");
            fputs($fp, "Host:$url[host]\r\n\r\n");
            $ret = '';
            while (!feof($fp)) {
                $tmp = fgets($fp);
                if (trim($tmp) == '') {
                    break;
                }
                $ret .= $tmp;
            }
            return $ret;
        } else {
            return null;
        }
    }

    private function htmlspecialchars_decode($str)
    {
    }
}
